const router = require('../../router');
const orderModel = require('../../../model/order')
const userModel = require('../../../model/user')
const courseModel = require('../../../model/course')
const sequelize = _loadSequelize();

router.get('/learn/course', async (ctx) => {

    // 根据订单获取所有已经购买父课程
    const result = await orderModel.findAll({
        where: {status: 1, userId: ctx.session.userLoginId},
        order: [['id', 'DESC']],
        include: [
            {
                model: userModel
            },
            {
                model: courseModel
            },
          ]
    })

    // 根据所有父课程获取所有子课程
    const resultPromise = []
    result.forEach(e => {
        const promiseItem = sequelize.query(`SELECT courseItems.*, courseItemLearns.learnTime FROM courseItems LEFT JOIN courseItemLearns ON (courseItemLearns.courseItemId = courseItems.id and courseItemLearns.userId = ${ctx.session.userLoginId}) where courseItems.courseId = ${e.course.id}`, {type: sequelize.QueryTypes.SELECT})
        resultPromise.push(promiseItem)
    })
    const courseItem = await Promise.all(resultPromise)

    for(let i = 0;  i<courseItem.length; i++) {
        if(courseItem[i].length > 0){
            let learnTime = 0
            let totalTime = 0
            courseItem[i].forEach(e => {
                learnTime += e.learnTime > e.time ? e.time : e.learnTime
                totalTime += e.time
            })
            const tempLearn = Math.floor(learnTime / totalTime * 100)
            result[i].learn = tempLearn >= 100 ? 100 : tempLearn
        }else{
            result[i].learn = 0
        }

    }


    const viewData = Object.assign(ctx.viewData, {
        category: 'course',
        list: result,
        courseItem:  await Promise.all(resultPromise)
    });
    ctx.body = await ctx.render('learn/course', viewData)
})